<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input v-model="dataForm.tenantName" placeholder="请输入租户名称" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查 询</el-button>
        <el-button v-if="isAuth('tenant:tenantInfo:save')" type="primary" plain @click="addOrUpdateHandle()">新 增</el-button>
        <el-button icon="iconfont icondaoru" v-if="isAuth('tenant:tenantInfo:list')" type="warning" plain @click="dialogVisible = true">批量导入</el-button>
        <el-button @click="showLogDialog" plain type="success">日志统计</el-button>
        <el-button @click="exportLog" type="success" plain>日志导出</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      :max-height="tableHeight"
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column
        type="index"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column
        prop="tenantName"
        header-align="center"
        align="center"
        min-width="210"
        label="租户名称">
      </el-table-column>
      <el-table-column
        prop="certificateCode"
        header-align="center"
        align="center"
        min-width="180"
        label="统一社会信用代码">
      </el-table-column>
      <el-table-column
        prop="businessEntity"
        header-align="center"
        align="center"
        min-width="80"
        label="企业法人">
      </el-table-column>
      <el-table-column
        prop="businessEntityMobile"
        header-align="center"
        align="center"
        min-width="110"
        label="法人手机号">
      </el-table-column>
      <el-table-column
        prop="contactPerson"
        header-align="center"
        align="center"
        min-width="80"
        label="联系人">
      </el-table-column>
      <el-table-column
        prop="contactPersonMobile"
        header-align="center"
        align="center"
        min-width="110"
        label="联系人手机号">
      </el-table-column>
      <el-table-column
        prop="address"
        header-align="center"
        align="center"
        min-width="150"
        :show-overflow-tooltip="true"
        label="租户地址">
      </el-table-column>
      <el-table-column
        prop="status"
        header-align="center"
        align="center"
        min-width="80"
        label="状态">
        <template slot-scope="scope">
          <span v-if="scope.row.status === 1">
            有效
          </span>
          <span v-if="scope.row.status === 0">
            无效
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        header-align="center"
        align="center"
        min-width="160"
        label="创建时间">
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        min-width="150"
        label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" style="color:#53b4ff" @click="addOrUpdateHandle(scope.row.tenantId)">修改</el-button>
          <el-button type="text" size="small" style="color:#53b4ff" @click="updateTenantHandle(scope.row.tenantId)">配置</el-button>
          <el-button type="text" size="small" style="color:red" @click="deleteHandle(scope.row.tenantId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[50, 100, 200]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    <tenant-conf v-if="tenantConfVisible" ref="tenantConf" ></tenant-conf>
    <el-dialog
      title="租户信息批量导入"
      :visible.sync="dialogVisible"
      width="30%">
      <span style="text-align: center;">
        <el-upload drag
            :limit=limitNum
            :headers="myHeader"
            :auto-upload="false"
            accept=".xlsx"
            :action="uploadUrl()"
            :before-upload="beforeUploadFile"
            :on-change="fileChange"
            :on-exceed="exceedFile"
            :on-success="handleSuccess"
            :on-error="handleError"
            :file-list="fileList">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text"><em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传xlsx文件，且不超过10M</div>
        </el-upload>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" plain @click="uploadFile()">导 入</el-button>
      </span>
    </el-dialog>
    <tenant-info-log v-if="logVisible" ref="logRefs"></tenant-info-log>
  </div>
</template>

<script>
  import AddOrUpdate from './tenantInfo-add-or-update'
  import TenantConf from './tenantinfo-conf'
  import Vue from 'vue'
  import TenantInfoLog from './TenantInfoLog'
  import {exportData} from '../../../api/customer/commom'
export default {
    data () {
      return {
        dataForm: {
          // key: ''
          tenantName: ''
        },
        dialogVisible: false,
        logVisible: false,
        dataList: [],
        pageIndex: 1,
        pageSize: 50,
        totalPage: 0,
        tableHeight: 0,
        heightis: 180,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        tenantConfVisible: false,
        limitNum: 1,  // 上传excell时，同时允许上传的最大数
        fileList: []   // excel文件列表
      }
    },
    components: {
      TenantInfoLog,
      AddOrUpdate,
      TenantConf
    },
    created () {
      this.getDataList()
      this.tackHeight()
    },
    computed: {
      myHeader () {
        return {
          'token': Vue.cookie.get('token')
        }
      }
    },
    methods: {
      tackHeight () {
        this.heightis = 185
        this.adjustTableHeight()
      },
      clickClone () {
        this.tenantConfVisible = false
      },
      adjustTableHeight () {
        this.$nextTick(() => {
          console.log(window.innerHeight)
          this.tableHeight = window.innerHeight - this.heightis
          // 后面的50：根据需求空出的高度，自行调整
          console.log(this.tableHeight)
        })
      },
      // 文件超出个数限制时的钩子
      exceedFile (files, fileList) {
        this.$message.warning(`只能选择 ${this.limitNum} 个文件，当前共选择了 ${files.length + fileList.length} 个`)
      },
      // 文件状态改变时的钩子
      fileChange (file, fileList) {
        this.fileList.push(file.raw)
      },
      // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
      beforeUploadFile (file) {
        let extension = file.name.substring(file.name.lastIndexOf('.') + 1)
        let size = file.size / 1024 / 1024
        if (extension !== 'xlsx') {
          this.$message.warning('只能上传后缀是.xlsx的文件')
        }
        if (size > 10) {
          this.$message.warning('文件大小不得超过10M')
        }
      },
      // 文件上传成功时的钩子
      handleSuccess (res, file, fileList) {
        this.$message.success('文件上传成功')
      },
      // 文件上传失败时的钩子
      handleError (err, file, fileList) {
        this.$message.error('文件上传失败')
      },
      uploadUrl () {
        return ''
      },
      uploadFile () {
        if (this.fileList.length === 0) {
          this.$message.warning('请上传文件')
        } else {
          let form = new FormData()
          form.append('file', this.fileList[0])
          this.$http({
            url: this.$http.adornUrl('/tenant/tenantInfo/import'),
            method: 'post',
            responseType: 'blob', // 防止返回乱码
            headers: {
              'Content-type': 'multipart/form-data', 'token': Vue.cookie.get('token')
            },
            data: form,
            showLoading: true
          }).then(({data}) => {
            if (data) {
              const link = document.createElement('a')
              let blob = new Blob([data], {type: 'application/vnd.ms-excel'})
              link.style.display = 'none'
              link.href = URL.createObjectURL(blob)
              let fileName = '租户信息未导入成功统计.xls'
              link.setAttribute('download', fileName)
              link.download = fileName // 下载的文件名
              document.body.appendChild(link)
              link.click()
              document.body.removeChild(link)
            }
          })
        }
      },
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/tenant/tenantInfo/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            // 'key': this.dataForm.key
            'tenantName': this.dataForm.tenantName
          })
        }).then(({data}) => {
          console.log(data)
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      updateTenantHandle (id) {
        this.tenantConfVisible = true
        this.$nextTick(() => {
          this.$refs.tenantConf.init(id)
        })
      },
      // 删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$confirm(`确定要${id ? '删除' : '批量删除'}吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/tenant/tenantInfo/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',

                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      showLogDialog () {
        this.logVisible = true
        this.$nextTick(() => {
          this.$refs.logRefs.init()
        })
      },
      exportLog () {
        exportData('/sys/count/tenant/export', {
          'tenantId': null,
          'tenantName': null,
          'certificateCode': null,
          'businessEntity': null,
          'businessEntityMobile': null
        }, '企业登录日志')
      }
    }
  }
</script>
<style lang="scss" scoped>

.mod-config{
    padding: 15px;
}
</style>

